const { pool } = require('../config/db');
const { success, error } = require('../utils/response');

exports.getList = async (req, res, next) => {
  try {
    const [cartItems] = await pool.query(
      `SELECT c.id, c.book_id as bookId, c.borrow_days as borrowDays,
              b.name, b.author, b.cover, b.price
       FROM cart c 
       JOIN books b ON c.book_id = b.id 
       WHERE c.user_id = ? 
       ORDER BY c.id DESC`,
      [req.userId]
    );

    success(res, cartItems);
  } catch (err) {
    next(err);
  }
};

exports.add = async (req, res, next) => {
  try {
    const { bookId, borrowDays = 14 } = req.body;
    const userId = req.userId;

    console.log('🛒 添加购物车请求:', { bookId, borrowDays, userId });

    // 参数验证
    if (!bookId) {
      console.log('❌ 缺少图书ID参数');
      return error(res, '缺少图书ID参数', 400);
    }

    const bookIdNum = parseInt(bookId);
    if (isNaN(bookIdNum) || bookIdNum <= 0) {
      console.log('❌ 无效的图书ID:', bookId);
      return error(res, '无效的图书ID', 400);
    }

    const borrowDaysNum = parseInt(borrowDays);
    if (isNaN(borrowDaysNum) || borrowDaysNum <= 0 || borrowDaysNum > 365) {
      console.log('❌ 无效的借阅天数:', borrowDays);
      return error(res, '无效的借阅天数', 400);
    }

    // 检查书籍是否存在
    const [books] = await pool.query('SELECT id, stock FROM books WHERE id = ?', [bookIdNum]);
    if (books.length === 0) {
      return error(res, '图书不存在', 404);
    }
    
    // 检查库存
    if (books[0].stock <= 0) {
      return error(res, '无库存', 400);
    }

    // 检查是否已在购物车中
    const [existingCart] = await pool.query(
      'SELECT id FROM cart WHERE user_id = ? AND book_id = ?',
      [userId, bookIdNum]
    );
    if (existingCart.length > 0) {
      return error(res, '已在借书车中', 400);
    }

    // 添加到购物车
    await pool.query(
      'INSERT INTO cart (user_id, book_id, borrow_days) VALUES (?, ?, ?)',
      [userId, bookIdNum, borrowDaysNum]
    );
    
    success(res, null, '添加成功');
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return error(res, '已在借书车中', 400);
    }
    next(err);
  }
};

exports.remove = async (req, res, next) => {
  try {
    const { id } = req.params;
    
    const [result] = await pool.query(
      'DELETE FROM cart WHERE id = ? AND user_id = ?',
      [id, req.userId]
    );
    
    if (result.affectedRows === 0) {
      return error(res, '购物车中无此商品', 404);
    }
    
    success(res, null, '移除成功');
  } catch (err) {
    next(err);
  }
};